package cn.com.headfree.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gta.edu.sdk.base.service.impl.BaseServiceImpl;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.RedisClusterUtil;

import cn.com.headfree.server.dao.IServerItemDao;
import cn.com.headfree.server.dto.ZuulServerItemDto;
import cn.com.headfree.server.entity.TZuulServerItem;
import cn.com.headfree.server.service.IServerItemService;
import cn.com.headfree.vo.ZuulRouteVo;
import io.netty.util.internal.StringUtil;

@Service("serverItemService")
public class ServerItemServiceImpl extends BaseServiceImpl<TZuulServerItem> implements IServerItemService {

	@Autowired
	private IServerItemDao serverItemDao;

	@Value("redis.zuul.route.item")
	private String redisZuulRouteItem;

	@Override
	public void findAsPage(String serverId, Integer isEable, Page<ZuulServerItemDto> page) {
		this.serverItemDao.findAsPage(serverId, isEable, page);
	}

	@Override
	public void refresh() {
		List<TZuulServerItem> list = this.serverItemDao.findAll();
		if (list.size() > 0) {
			List<ZuulRouteVo> voList = new ArrayList<ZuulRouteVo>(list.size());
			ZuulRouteVo vo = null;
			for (TZuulServerItem item : list) {
				vo = new ZuulRouteVo();
				vo.setApiName(item.getName());
				vo.setEnabled(true);
				vo.setId(item.getId());
				vo.setPath(item.getPath());
				vo.setRetryable(false);
				vo.setServiceId(StringUtil.isNullOrEmpty(item.getServiceId())?null:item.getServiceId());
				vo.setStripPrefix(item.getStripPrefix() == 1 ? true : false);
				vo.setUrl(StringUtil.isNullOrEmpty(item.getUrl())?null:item.getUrl());
				voList.add(vo);
			}
			RedisClusterUtil.getInstance().setString(redisZuulRouteItem,net.sf.json.JSONArray.fromObject(voList).toString());
		}
	}

}
